package seed.web.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import seed.domain.Seed;
import seed.service.SeedService;


import category.domain.Category;
import category.service.CategoryService;


import cn.itcast.commons.CommonUtils;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class AdminAddSeedServlet2 extends HttpServlet {

	private SeedService seedService = new SeedService();
	private CategoryService categoryService = new CategoryService();
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		

			request.setCharacterEncoding("utf-8");
			response.setContentType("textml;charset=utf-8");
//			//转化编码格式
//			byte[] bytes = username.getBytes("ISO-8859-1");
//			username = new String(bytes, "GB2312");
			
			
			SmartUpload su = new SmartUpload();
			String fileName = "";
			//PageContext是jsp的内置对象，在servlet不能直接使用，需要做一些处理
	        JspFactory _jspxFactory = null;
	        PageContext pageContext = null;
	        _jspxFactory = JspFactory.getDefaultFactory();
	        pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);

			su.initialize(pageContext);//初始化
			su.setCharset("utf-8");//编码格式
			try {
				su.upload();//上传
				File file = su.getFiles().getFile(0);//获取第一个文件
				fileName = file.getFileName();//获取文件名
				//String url =request.getContextPath();
				//String url1 =request.getServletPath();
				file.saveAs("upfile/"+fileName);//文件另存为
			} catch (SmartUploadException e) {
				e.printStackTrace();
			}
			Request req = su.getRequest();
			
			SeedService seedSerivce = new SeedService();
			Seed seed = CommonUtils.toBean(request.getParameterMap(), Seed.class);
			seed.setSid(CommonUtils.uuid());
			//String image = req.getParameter("image");
			
			seed.setSname(req.getParameter("sname")) ;
			seed.setImage(fileName) ;
			seed.setPrice(Integer.parseInt(req.getParameter("price"))) ;
			seed.setLarge(Double.parseDouble(req.getParameter("large"))) ;
			seed.setXiangxi(req.getParameter("xiangxi")) ;
			seed.setYaodian(req.getParameter("yaodian")) ;
			//seed.setCategory(req.getParameter("cid"));
			Category category = CommonUtils.toBean(request.getParameterMap(), Category.class);
			seed.setCategory(category);
			
			//seed.setImage(image);
			//System.out.println("!!!!!!!!!sname:"+sname);
			

			
			// 为seed指定sid
			seed.setSid(CommonUtils.uuid());
			
			seedService.add(seed);
			
			request.getRequestDispatcher("/AdminSeedServlet?method=findAll")
			.forward(request, response);
			
		}

	}


